<?php
/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * For more information, see <http://www.aljey.com>.
 */

namespace Al\Core\Lib;

/**
 * Allows to register, re-register, un-register and use services.
 * Which are factories returning specific instances.
 *
 * @author Eugene Kuzmenko <mail@aljey.com>
 */
class Service extends ParameterHolder {

  /**
   * @var Service
   */
  private static $me;

  /**
   * @var array
   */
  protected $event = array();

  /**
   * @var array A collection of service names being initialized.
   */
  protected $loading = array();

  /**
   * @var array A collection of initialized service names.
   */
  protected $loaded = array();

  /**
   * Returns a service config.
   *
   * @param string $name [optional] A dot-separated name.
   * @param mixed $default [optional] Default value.
   * @return mixed
   */
  public static function get($name = '', $default = null) {
    if (!self::$me) self::$me = new Service;
    if (!strlen($name)) return self::$me;
    $ns = explode('.', $name);
    $service = self::$me;
    foreach ($ns as $key) {
      if (is_array($service) || $service instanceof \ArrayAccess) {
        if (!isset($service[$key])) return $default;
        $service = $service[$key];
      } elseif (isset($service->$key)) {
        $service = $service->$key;
      } elseif (is_callable(array($service, $key = "get$key"))) {
        $service = $service->$key();
      } else {
        return $default;
      }
    }
    return $service;
  }

  /**
   * Returns a value container reference by name.
   *
   * @param string $name [optional] A dot-separated name.
   * @return bool|mixed|null
   */
  protected static function &getWriteContainer($name = '') {
    $fail = false;
    if (!self::$me) self::$me = new Service;
    if (!strlen($name)) return self::$me;
    $ns = explode('.', $name);
    $last = array_pop($ns);
    $service = self::$me;
    foreach ($ns as $key) {
      if (is_array($service) || $service instanceof \ArrayAccess) {
        if (!isset($service[$key])) return $fail;
        $service = &$service[$key];
      } elseif (isset($service->$key)) {
        $service = &$service->$key;
      } else {
        return $fail;
      }
    }
    if (!$service) return $fail;
    if (is_array($service) || $service instanceof \ArrayAccess) {
      if (!isset($service[$last])) $service[$last] = null;
      $resp = &$service[$last];
      return $resp;
    } else {
      try {
        if (!isset($service->$last)) $service->$last = null;
        return $service->$last;
      } catch (\Exception $e) { return $fail; }
    }
  }

  /**
   * Merges two values together recursively.
   *
   * @param mixed $target A reference to the target.
   * @param mixed $source A source.
   * @param bool $overwrite [optional] True to overwrite non-null values.
   */
  public static function mergeRecursive(&$target, $source, $overwrite = true) {
    if (!is_array($target) && !($target instanceof \ArrayAccess)) {
      if (null === $target || $overwrite) $target = $source;
      return;
    }
    if (!is_array($source) && !($source instanceof \ArrayAccess)) return;
    foreach ($source as $key => $value) {
      if (is_numeric($key)) {
        $target[] = $value;
        continue;
      }
      if (isset($target[$key])) {
        self::mergeRecursive($target[$key], $value);
      } else {
        $target[$key] = $value;
      }
    }
  }

  /**
   * Sets a container value by name.
   *
   * @param string $name [optional] A dot-separated name.
   * @param mixed $value [optional]
   */
  public static function set($name = '', $value = null) {
    if (!is_string($name)) {
      $value = $name;
      $name = '';
    }
    self::mergeRecursive(self::getWriteContainer($name), $value);
  }

  /**
   * Sets a container value by name, but only if it has not been set before.
   *
   * @param string $name [optional] A dot-separated name.
   * @param mixed $value [optional]
   */
  public static function setIf($name = '', $value = null) {
    if (!is_string($name)) {
      $value = $name;
      $name = '';
    }
    self::mergeRecursive(self::getWriteContainer($name), $value, false);
  }

  /**
   * Called whenever someone tries to $obj[$offset].
   *
   * @param mixed $offset An array key.
   * @return mixed The requested value.
   */
  public function offsetGet($offset) {
    if (!$this->offsetExists($offset)) return null;
    if (!is_callable($value = $this->data[$offset])) return $value;
    if (isset($this->loading[$offset])) {
      throw new \RuntimeException("The service $offset depends on the existence"
        . ' of itself, please see Service::when');
    }
    $this->loading[$offset] = true;
    $this->data[$offset] = call_user_func($value, $this);
    if (isset($this->event[$offset])) {
      foreach ($this->event[$offset] as $value) {
        call_user_func($value, $this->data[$offset], $this);
      }
      unset($this->event[$offset]);
    }
    unset($this->loading[$offset]);
    $this->loaded[$offset] = true;
    return $this->data[$offset];
  }

  /**
   * Registers a service.
   *
   * @param string $offset A service name.
   * @param callable $value A factory function.
   */
  public function offsetSet($offset, $value) {
    if (!is_callable($value)) {
      throw new \InvalidArgumentException('A service factory must be callable');
    }
    parent::offsetSet($offset, $value);
  }

  /**
   * Registers an event listener for when the service is initialized.
   *
   * @param string $name
   * @param callable $handler
   */
  public function when($name, $handler) {
    if (!is_callable($handler)) {
      throw new \InvalidArgumentException('An event handler must be callable');
    }
    if (isset($this->loaded[$name])) {
      call_user_func($handler, $this->data[$name], $this);
    } else {
      if (!isset($this->event[$name])) $this->event[$name] = array();
      $this->event[$name][] = $handler;
    }
  }

} 